package com.hgb.mall.admin.services.impl;

import com.github.pagehelper.PageHelper;
import com.hgb.mall.admin.services.UmsResourceService;
import com.hgb.mall.common.constant.AuthConstant;
import com.hgb.mall.common.service.RedisService;
import com.hgb.mall.mbg.entity.UmsResource;
import com.hgb.mall.mbg.entity.UmsRole;
import com.hgb.mall.mbg.entity.UmsRoleResourceRelation;
import com.hgb.mall.mbg.mapper.UmsResourceDynamicSqlSupport;
import com.hgb.mall.mbg.mapper.UmsResourceMapper;
import com.hgb.mall.mbg.mapper.UmsRoleMapper;
import com.hgb.mall.mbg.mapper.UmsRoleResourceRelationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static org.mybatis.dynamic.sql.SqlBuilder.isEqualToWhenPresent;
import static org.mybatis.dynamic.sql.SqlBuilder.isLikeWhenPresent;

/**
 * 后台资源管理Service实现类
 * Created by hgb on 2020/2/2.
 */
@Service
public class UmsResourceServiceImpl implements UmsResourceService {
    @Autowired
    private UmsResourceMapper resourceMapper;
    @Autowired
    private UmsRoleMapper roleMapper;
    @Autowired
    private UmsRoleResourceRelationMapper roleResourceRelationMapper;
    @Autowired
    private RedisService redisService;
    @Value("${spring.application.name}")
    private String applicationName;

    @Override
    public int create(UmsResource umsResource) {
        umsResource.setCreateTime(new Date());
        int count = resourceMapper.insert(umsResource);
        initResourceRolesMap();
        return count;
    }

    @Override
    public int update(Long id, UmsResource umsResource) {
        umsResource.setId(id);
        int count = resourceMapper.updateByPrimaryKeySelective(umsResource);
        initResourceRolesMap();
        return count;
    }

    @Override
    public UmsResource getItem(Long id) {
        return resourceMapper.selectByPrimaryKey(id).orElse(null);
    }

    @Override
    public int delete(Long id) {
        int count = resourceMapper.deleteByPrimaryKey(id);
        initResourceRolesMap();
        return count;
    }

    @Override
    public List<UmsResource> list(Long categoryId, String nameKeyword, String urlKeyword, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);


        return resourceMapper
                .select(c -> c.where(UmsResourceDynamicSqlSupport.categoryId, isEqualToWhenPresent(categoryId))
                              .and(UmsResourceDynamicSqlSupport.name, isLikeWhenPresent(nameKeyword)
                                      .then(s -> "%" + s + "%"))
                              .and(UmsResourceDynamicSqlSupport.url, isLikeWhenPresent(urlKeyword)
                                      .then(s -> "%" + s + "%")));
    }

    @Override
    public List<UmsResource> listAll() {
        return resourceMapper.select(c -> c);
    }

    @Override
    public Map<String, List<String>> initResourceRolesMap() {
        Map<String, List<String>> resourceRoleMap = new TreeMap<>();
        List<UmsResource> resourceList = resourceMapper.select(c -> c);
        List<UmsRole> roleList = roleMapper.select(c -> c);
        List<UmsRoleResourceRelation> relationList = roleResourceRelationMapper.select(c -> c);
        for (UmsResource resource : resourceList) {
            Set<Long> roleIds = relationList.stream().filter(item -> item.getResourceId().equals(resource.getId()))
                                            .map(UmsRoleResourceRelation::getRoleId).collect(Collectors.toSet());
            List<String> roleNames = roleList.stream().filter(item -> roleIds.contains(item.getId()))
                                             .map(item -> item.getId() + "_" + item.getName())
                                             .collect(Collectors.toList());
            resourceRoleMap.put("/" + applicationName + resource.getUrl(), roleNames);
        }
        redisService.del(AuthConstant.RESOURCE_ROLES_MAP_KEY);
        redisService.hSetAll(AuthConstant.RESOURCE_ROLES_MAP_KEY, resourceRoleMap);
        return resourceRoleMap;

    }
}
